import {createWebHistory,createRouter} from "vue-router";
import Cookies from 'js-cookie'
const routes =[
    {
        path:"/login",
        name:"Login",
        component:()=>import("../components/Login.vue")
    },
    {
        path:"/",
        name:"Index",
        component:()=>import("../components/Index.vue"),
        redirect:"/dashboard",
        meta:{
            requiresAuth:true
        },
        children: [
            {
                path:"/dashboard",
                name:"Dashboard",
                component:()=>import("../components/admin/Dashboard.vue")
            },
            {
                path:"/code",
                name:"CodeManagement",
                component:()=>import("../components/admin/CodeManagement.vue")
            },
            {
                path:"/user",
                name:"UserManagement",
                component:()=>import("../components/admin/UserManagement.vue")
            },
            {
                path: "/model",
                name: "ModelManagement",
                component: () => import("../components/admin/ModelManagement.vue")
            }
            ]
    },
]
const router = createRouter({
    history:createWebHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    // 这里是 'requiresAuth', 不是 'requireAuth'
    if (to.meta.requiresAuth) {
        const token = Cookies.get('username')
        if (token) {
            next(); // 用户已登录，允许访问路由
        } else {
            next({
                path: "/login",
                query: { redirect: to.fullPath } // 将用户重定向到登录页面，并附带重定向前的完整路径
            });
        }
    } else {
        next(); // 路由不需要认证，直接允许访问
    }
});

export default router